package com.seedwill.common.dozer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dozer.ConfigurableCustomConverter;
import org.dozer.converters.ConversionException;

/**
 * DOZER转换器
 * 
 * 自定义日期格式转换
 * 
 * @author kdyi
 * 
 */
public class CustomDateConverter implements ConfigurableCustomConverter {
	protected Log log = LogFactory.getLog(this.getClass());

	public CustomDateConverter() {
	}

	private String parameter;

	public String getParameter() {
		return parameter;
	}

	public void setParameter(String parameter) {
		this.parameter = parameter;
	}

	public Object convert(Object existingDestinationFieldValue,
			Object sourceFieldValue, Class destClass, Class sourceClass,
			String dateFormat) {
		Object result = null;
		if (sourceFieldValue != null) {
			if (sourceClass.isAssignableFrom(String.class)) {
				// 字符串转为日期
				try {
					result = DateTimeConverterSupport.toDate(dateFormat,
							(String) sourceFieldValue);
				} catch (Exception e) {
					throw new ConversionException(e);
				}
			} else {
				// 日期转为字符串
				try {
					result = DateTimeConverterSupport.formatDate(dateFormat,
							(java.util.Date) sourceFieldValue);
				} catch (Exception e) {
					throw new ConversionException(e);
				}
			}
		}
		return result;
	}

	public Object convert(Object existingDestinationFieldValue,
			Object sourceFieldValue, Class<?> destinationClass,
			Class<?> sourceClass) {
		try {
			return convert(existingDestinationFieldValue, sourceFieldValue,
					destinationClass, sourceClass, parameter);
		} catch (RuntimeException e) {
			log.warn(
					"Data convert exception[existingDestinationFieldValue:"
							+ existingDestinationFieldValue+(existingDestinationFieldValue !=null ? "("+existingDestinationFieldValue.getClass()+")" : "") + "]"
							+ "[sourceFieldValue:" + sourceFieldValue +(sourceFieldValue !=null ? "("+sourceFieldValue.getClass()+")" : "")+ "]"
							+ "[destinationClass:" + destinationClass + "]"
							+ "[sourceClass:" + sourceClass + "]", e);
			throw e;
		}
	}
}
